package cn.edu.nuc.crm.controller;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.edu.nuc.crm.dto.CarPlanShow;
import cn.edu.nuc.crm.dto.PageInfo;
//import cn.edu.nuc.crm.dto.PageInfo;
import cn.edu.nuc.crm.entity.Account;
import cn.edu.nuc.crm.entity.Application;
import cn.edu.nuc.crm.entity.Product;
import cn.edu.nuc.crm.entity.Repay;
import cn.edu.nuc.crm.entity.Repayment;
import cn.edu.nuc.crm.service.interfaces.AccountService;
import cn.edu.nuc.crm.service.interfaces.ApplicationService;
import cn.edu.nuc.crm.service.interfaces.CarPlanService;
import cn.edu.nuc.crm.service.interfaces.ProductService;
import cn.edu.nuc.crm.service.interfaces.RepayService;
import cn.edu.nuc.crm.service.interfaces.RepaymentService;
@Controller
public class AccountController {
	@Autowired
	private AccountService accountService;
	@Autowired
	private ProductService productService;
	@Autowired
	private CarPlanService carPlanService;
	@Autowired
	private ApplicationService applicationService;
	@Autowired
	private RepaymentService repaymentService;
	@Autowired
	private RepayService repayService;
	
	@RequestMapping(value="/register",method=RequestMethod.GET)
	public String register(){
		return "register";
	}
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String register(Account account,Model model,HttpServletResponse res,HttpServletRequest req){
		try{
			accountService.register(account);
			return "/login1";
		}
		catch(Exception e){
			e.printStackTrace();
	}	
		model.addAttribute("msg", "注册失败");
		return "/login1";	
	}
	/**
	 * 列出用户列表
	 * @param current
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/accountlist",method=RequestMethod.GET)
	public String select(@RequestParam(name="current",defaultValue="1") int current,
			HttpSession session, Model model){	
		try {
			List<Account> account = new ArrayList<Account>();
			account = accountService.account();
			session.setAttribute("account", account);
			PageInfo pi = accountService.account(current);
			System.out.println("sddsd" + pi.getList());
			session.setAttribute("pi", pi);
			
			return "accountlist";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "accountlist";
	}
	/**
	 * 列出单个用户
	 * @param current
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/accountlist1",method=RequestMethod.GET)
	public String select1(@RequestParam(name="current",defaultValue="1") int current,
			HttpSession session, Model model){	
		try {
			Account account = new Account();
			account = (Account) session.getAttribute("account");
			PageInfo pi = accountService.account1(account.getAccountname(),current);
			System.out.println("sddsd" + pi.getList());
			session.setAttribute("pi", pi);
			
			return "account/accountlist1";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "account/accountlist1";
	}
	/**
	 * 增加用户
	 * @return
	 */
	@RequestMapping(value="account/add",method=RequestMethod.GET)
	public  String add(){
		return "account/add";		
	}
	@RequestMapping(value="accountadd",method=RequestMethod.POST)
	public String add(Account account,HttpServletRequest request){
		try{
		accountService.insert(account);
		return "accountlist";
		}catch(Exception e){
		  request.setAttribute("msg", "添加失败");
		  return "account/add";
		}
	}
	//数据校验
	/*@RequestMapping(value="/validate")
	   @RequestMapping(value="/test", method = {RequestMethod.GET})
		    public String test(Model model){
		        if(!model.containsAttribute("contentModel")){
		            model.addAttribute("contentModel", new ValidateModel());
		        }
		        return "validatetest";
		    }	    
		    @RequestMapping(value="/test", method = {RequestMethod.POST})
	      public String test(Model model, @Valid @ModelAttribute("contentModel") ValidateModel validateModel, BindingResult result) throws NoSuchAlgorithmException{	        
		        //如果有验证错误 返回到form页面
		        if(result.hasErrors())
		         return test(model);
		        return "adminlist";     
		    }*/
	/**
	 * 通过名字属性查找客户
	 * @param model
	 * @param accountname
	 * @return
	 */
	@RequestMapping(value="/accountsearch",method=RequestMethod.POST)
	public String selectByName(Model model,String accountname){
		System.out.println(accountname);
		if( accountname != null && !accountname.equals("") ){
			List<Account> list = accountService.selectByName(accountname);
			model.addAttribute("list", list);
			return "/account/search";
		}
		return "redirect:accountlist";		
		}
	/**
	 * 删除客户
	 * @param accountid
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/accountdelete",method=RequestMethod.GET)
	public String delete(Integer accountid,HttpSession session){
		int result=accountService.deleteByPrimaryKey(accountid);
		if(result>0){
			return "redirect:accountlist";	
		}else{
			session.setAttribute("info", "该用户不能删除");
			return "/accountlist";
		}
	}	
	/**
	 * 编辑客户
	 * @param funid
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/account/edit",method=RequestMethod.GET)
	public String update(int accountid,HttpSession session){
		Account account=accountService.selectByPrimaryKey(accountid);
		System.out.println(account);
		session.setAttribute("item",account) ;
		return "account/edit";		
	}
	/**
	 * 编辑客户1
	 * @param funid
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/account/edit1",method=RequestMethod.GET)
	public String update1(int accountid,HttpSession session){
		Account account=accountService.selectByPrimaryKey(accountid);
		System.out.println(account);
		session.setAttribute("item",account) ;
		return "account/edit1";		
	}
	// Account a Model model
	@RequestMapping(value="/accountedit",method=RequestMethod.POST)
	public String updatefun(HttpServletRequest request,Account account){
		try{
		accountService.updateByPrimaryKeySelective(account);
		return "redirect:accountlist";
		}catch(Exception e){
			request.setAttribute("msg", "修改失败");
			return "account/edit";
		}	
	}
	@RequestMapping(value="/accountedit1",method=RequestMethod.POST)
	public String updatefun1(HttpServletRequest request,Account account){
		try{
		accountService.updateByPrimaryKeySelective(account);
		return "redirect:accountlist1";
		}catch(Exception e){
			request.setAttribute("msg", "修改失败");
			return "account/edit1";
		}	
	}
	@RequestMapping(value="/account",method=RequestMethod.GET)
	public	String acc(String accountname,HttpServletRequest request){
		
		List<Account> list=accountService.selectByName(accountname);
		request.setAttribute("pi", list);
		return "account";	
	}
	
	@RequestMapping(value="/toproductsearch",method=RequestMethod.POST)
	public String search(Model model,String productname){
		System.out.println(productname);
	if( productname != null && !productname.equals("") ){
			List<Product> list = productService.selectByName(productname);
			model.addAttribute("list", list);
			return "cartlist";
		}
		return "redirect:productlist";	
   }
	
	@RequestMapping(value="/product/list",method=RequestMethod.GET)
	public String product(Model model,String productname){
		System.out.println(productname);
	if( productname != null && !productname.equals("") ){
			List<Product> list = productService.selectByName(productname);
			System.out.println("list---------------" +list);
			model.addAttribute("list", list);
			return "productlist2";
		}else{
			
			List<Product> list= productService.product();
			model.addAttribute("pi1", list);
			return "productlist2";	
		}
		
   }
	@RequestMapping(value="/accounthelp",method=RequestMethod.GET)
	public String accounthelp(){	
		
		return "account/help";
	}
	@RequestMapping(value="/carhome",method=RequestMethod.GET)
	public String carhome(){	
		
		return "account/home";
	}
	@RequestMapping(value="/car",method=RequestMethod.POST)
	public String car(String city,HttpSession session){
		// 这边的city  就是吃的看款式
		
		System.out.println(city+"---jihe-"+city);
		if(city!= null && city!= null){
		  session.setAttribute("carName", city);
		  List<CarPlanShow> list = carPlanService.find(city);
		  //低息贷
		  List<CarPlanShow> list1 = new ArrayList<>();
		  //短期贷
		  List<CarPlanShow> list2 = new ArrayList<>();
		  for(int i= 0;i<3;i++){
			  if(i == 0 || i == 1){
				  list1.add(list.get(i));
			  }
			
			  		
			  if(i == 2){
				  list2.add(list.get(i));
				  
			  }
			  
		  }
		   session.setAttribute("plancar1", list1);
		   session.setAttribute("plancar2", list2);
		   //默认贷款价格
		   String bj = carPlanService.findbj(city);
		   Double dbjp =  Double.parseDouble(bj);
		   DecimalFormat   df   =new  DecimalFormat("#.00");
		   String csdk =String.valueOf(df.format(dbjp*0.5));
		   session.setAttribute("csdk",csdk);
			return "account/choose";
		}
		return "account/home";
	}
	//贷款金额
	@RequestMapping(value="/dkje",method=RequestMethod.POST)
	public String dkje(String dkje,HttpSession session){
		// 这边的city  就是吃的看款式
		   
		if(dkje!= null ){
		  String carName = (String) session.getAttribute("carName");	
		  List<CarPlanShow> list = carPlanService.find1(dkje,carName);
		  //低息贷
		  List<CarPlanShow> list1 = new ArrayList<>();
		  //短期贷
		  List<CarPlanShow> list2 = new ArrayList<>();
		  for(int i= 0;i<3;i++){
			  if(i == 0 || i == 1){
				  list1.add(list.get(i));
			  }
			
			  		
			  if(i == 2){
				  list2.add(list.get(i));
				  
			  }
			  
		  }
		   session.setAttribute("plancar1", list1);
		   session.setAttribute("plancar2", list2);
		   
		   session.setAttribute("getdkje", dkje);
		   
			return "account/choose";
		}
		return "account/home";
	}
	//贷款方式
	@RequestMapping(value="/dkfs",method=RequestMethod.GET)
	public String dkfs(String carName,String regplan,String terminally
			,String total,HttpSession session){
		
		if(regplan!= null & terminally!= null & total!= null & carName!= null){
		    
			Account sessionAccount = (Account) session.getAttribute("account");
			Account newAccount = accountService.selectByPrimaryKey(sessionAccount.getAccountid());
			
			String getdkje =(String) session.getAttribute("getdkje");
			
			Application apt = new Application();
			
			apt.setAptTrueName(newAccount.getAccountrname());
			apt.setAccountId(newAccount.getAccountid());
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			apt.setAptTime(df.format(new Date()));
			//标价
			String bj = carPlanService.findbj(carName);
			apt.setAptAmount(bj);
			
			//贷款
			if(getdkje == null){
				apt.setAptBuyCar(session.getAttribute("csdk").toString());
			}else{
				apt.setAptBuyCar(getdkje);
			}
			
			apt.setAptCar(carName);
			
			apt.setAptTerminally(terminally);
			apt.setAptRegplan(regplan);
			apt.setAptTotal(total);
			
			//一些后续的设置为初始状态为 0
			apt.setAptStatus(0);  //受力状态  0：没有审核
			apt.setAptFksh(0);    //付款审核    0：没有审核
			apt.setAptYwzgsh(0);  //业务主管审核  0：没有审核
			apt.setAptCwsh(0);    // 财务审核 0：没有审核
			apt.setAptDysh(0);		// 抵押审核 0：没有审核
			//设置流程  1:风控  ;2: 财务; 3: 抵押; 4: 业务主管
			apt.setAptStatus(1);
			//还款信息
//			Repayment repayment = new Repayment();
//			
//			repayment.setAccountId(account.getAccountid());
//			repayment.setAccountTruename(account.getAccountrname());
//			repayment.setRepaymentPlan(regplan);
//			repayment.setRepaymentTime(null);
//			repayment.setRepaymentUrges(0); // 0:还没有受理   等待审批   1：可以还款了  2：催促还款
//			repayment.setRepaymentTotal(total);
//			
//			repaymentService.insert(repayment);
			
			
			
			session.setAttribute("buycarapt", apt);
			return "account/choosesuccess";
		}
		return "account/home";
	}
	
	// 续保押金 和保证金
	@RequestMapping(value="/xubaozheng",method=RequestMethod.POST)
	public String xubaozheng(String xubaojine,String baozhengjine,HttpSession session){
		if(xubaojine!=null && baozhengjine!=null){
			Application application = (Application)session.getAttribute("buycarapt");
			application.setAptAccountBzj(baozhengjine);
			application.setAptAccountXbyj(xubaojine);
			
			applicationService.insert(application);
			
			
		}
		return "account/home";
	}
	
	@RequestMapping(value="/repaymentAccount",method=RequestMethod.GET)
	public String repaymentAccount(@RequestParam(name="current",defaultValue="1") int current,
			HttpSession session, Model model){	
		try {
			Account account = (Account) session.getAttribute("account");
			PageInfo pi = repaymentService.accountRepayment(account.getAccountid(),current);
			session.setAttribute("pi", pi);	
			
			return "account/repaymentAccount";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "accountlist";
	}
	
	
	//访问车贷网官网首页
	@RequestMapping(value="/index",method=RequestMethod.GET)
	public String index(){	
		
		return "qiantai/index";
	}
	//访问车贷网官网首页
	@RequestMapping(value="/registe",method=RequestMethod.GET)
	public String registe(){	
			
		return "qiantai/regist";
	}
	@RequestMapping(value="/registeAccount",method=RequestMethod.POST)
	public String registerAccount(String accountname,String accountpassword,String accountphone,Model model,HttpServletResponse res,HttpServletRequest req){
		try{
			Account account = new Account();
			account.setAccountname(accountname);
			account.setAccountpassword(accountpassword);
			account.setAccountphone(accountphone);
			account.setRoleid(2);
			accountService.register(account);
			return "/login1";
		}
		catch(Exception e){
			e.printStackTrace();
			
	}	
		model.addAttribute("msg", "注册失败");
		return "/login1";	
	}
	//访问车贷网官网登陆
	@RequestMapping(value="/loginindex",method=RequestMethod.GET)
	public String loginindex(){
				
		return "qiantai/qtlogin";
	}
	//车贷网
	
	@RequestMapping(value="/seecar",method=RequestMethod.GET)
	public String seecar(){
				
		return "qiantai/home";
	}
	@RequestMapping(value="/car1",method=RequestMethod.POST)
	public String car1(String city,HttpSession session){
		// 这边的city  就是吃的看款式
		
		System.out.println(city+"---jihe-"+city);
		if(city!= null && city!= null){
		  session.setAttribute("carName", city);
		  List<CarPlanShow> list = carPlanService.find(city);
		  //低息贷
		  List<CarPlanShow> list1 = new ArrayList<>();
		  //短期贷
		  List<CarPlanShow> list2 = new ArrayList<>();
		  for(int i= 0;i<3;i++){
			  if(i == 0 || i == 1){
				  list1.add(list.get(i));
			  }
			
			  		
			  if(i == 2){
				  list2.add(list.get(i));
				  
			  }
			  
		  }
		   session.setAttribute("plancar1", list1);
		   session.setAttribute("plancar2", list2);
		   
			return "qiantai/choose";
		}
		return "qiantai/home";
	}
	
	//贷款金额
	@RequestMapping(value="/dkje1",method=RequestMethod.POST)
	public String dkje1(String dkje1,HttpSession session){
		// 这边的city  就是吃的看款式
		   
		if(dkje1!= null ){
		  String carName = (String) session.getAttribute("carName");	
		  List<CarPlanShow> list = carPlanService.find1(dkje1,carName);
		  //低息贷
		  List<CarPlanShow> list1 = new ArrayList<>();
		  //短期贷
		  List<CarPlanShow> list2 = new ArrayList<>();
		  for(int i= 0;i<3;i++){
			  if(i == 0 || i == 1){
				  list1.add(list.get(i));
			  }
			
			  		
			  if(i == 2){
				  list2.add(list.get(i));
				  
			  }
			  
		  }
		   session.setAttribute("plancar1", list1);
		   session.setAttribute("plancar2", list2);
		   
		   session.setAttribute("getdkje", dkje1);
		   
			return "qiantai/choose";
		}
		return "qiantai/home";
	}
	//个人贷款
	
	@RequestMapping(value="/grdk",method=RequestMethod.GET)
	public String grdk(@RequestParam(name="current",defaultValue="1") int current,HttpSession session){
		Account account = (Account) session.getAttribute("account");
		PageInfo pi =applicationService.selectByCountId(current,account.getAccountid());
		session.setAttribute("pi", pi);
		
		return "account/grapt";
	
	}
	//偿还贷款
	@RequestMapping(value="/repayaloan",method=RequestMethod.GET)
	public String chdk(@RequestParam(name="current",defaultValue="1") int current,HttpSession session){
		Account account = (Account) session.getAttribute("account");
		PageInfo pi = repayService.selectByCountId(current,account.getAccountid());
		session.setAttribute("pi", pi);
		
		return "account/repayaloan";
	
	}
	///定期偿还
	@RequestMapping(value="/repayaloanAccount",method=RequestMethod.GET)
	public String repayaloanAccount(int accountId,int id,HttpSession session){
		Repay repay = new Repay();
		repay.setAccountId(accountId);
		repay.setId(id);
		Repay AccountRepay=repayService.selectByPrimaryKey(repay);
		session.setAttribute("AccountRepay", AccountRepay);
		
		return "account/repayaloanAccount";
	
	}
	///消减钱财
	@RequestMapping(value="/repayaloanEdit",method=RequestMethod.POST)
	public String repayaloanEdit(Repay repay,HttpSession session){
		
		DecimalFormat   df   =new  DecimalFormat("#.00");
		Double Syrmb =  new Double(0);
		Double Yhrmb =  new Double(0);
		String sy = repay.getRepaySyrmb();
		String yh = repay.getRepayYhrmb();
		if(sy==null || sy ==""){
			Syrmb = Double.parseDouble("0");
		}else{
			Syrmb = Double.parseDouble(repay.getRepaySyrmb());
		}
		if(yh==null || yh ==""){
			Yhrmb =  Double.parseDouble("0");
		}else{
			Yhrmb = Double.parseDouble(repay.getRepayYhrmb());
		}
		
			Double Ter =  Double.parseDouble(repay.getRepaymentTerminally());
			Double total =  Double.parseDouble(repay.getRepaymentTotal());
			Double ssy =  total-Ter-Yhrmb;	
			Double yyh =  Ter+Yhrmb;
			repay.setRepaySyrmb(String.valueOf(df.format(ssy)));
			repay.setRepayYhrmb(String.valueOf(df.format(yyh)));
			repayService.updateByPrimaryKey(repay);
			
		
	
		
		
		return "redirect:/repayaloan";
		
	}
	//管理员查看客户还款记录
	@RequestMapping(value="/repayaloanSee",method=RequestMethod.GET)
	public String repayaloanSee(@RequestParam(name="current",defaultValue="1") int current,HttpSession session){

		PageInfo pi =repayService.select(current);
		session.setAttribute("pi", pi);
		
		return "account/repayaloan";
		
	}
}
